﻿using System.Data;
using Lite = System.Data.SQLite;

namespace SMSRulez
{
    sealed class DB
    {
        internal string connectionString = string.Empty;
        public DB(string location)
        {
            connectionString = "Data Source = " + location + @"\Rules.db;";
        }
        public enum sqlAction { Insert, Update, Delete, Select, Create };
        public bool SetConnection(string command, sqlAction action,out DataTable tableRule)
        {
            tableRule = new DataTable();
            tableRule.Clear();
            bool success = true;
            using (Lite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection(connectionString))
            {
                using (Lite.SQLiteDataAdapter adapter = new System.Data.SQLite.SQLiteDataAdapter())
                {
                    using (Lite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand())
                    {
                        try
                        {
                            cmd.Connection = conn;
                            cmd.CommandText = command;// "SELECT NAME, ALARM FROM Location order by NAME ASC";
                            cmd.Connection.Open();
                            switch (action)
                            {
                                case sqlAction.Select:
                                    adapter.SelectCommand = cmd;
                                    adapter.Fill(tableRule);
                                    break;
                                case sqlAction.Delete:
                                    adapter.DeleteCommand = cmd;
                                    break;
                                case sqlAction.Insert:
                                    adapter.InsertCommand = cmd;
                                    break;
                                case sqlAction.Update:
                                    adapter.UpdateCommand = cmd;
                                    break;
                                case sqlAction.Create:
                                    break;
                            }
                            cmd.ExecuteNonQuery();
                        }

                        catch (Lite.SQLiteException ex)
                        {
                            string test = ex.Message;
                            success = false;
                        }
                        finally
                        {
                            cmd.Connection.Close();
                        }
                        return success;
                    }
                }
            }
        }
    }
}